import fs from 'fs';
import path from 'path';
import crypto from 'crypto';

// 生成唯一文件名
export function generateUniqueFileName(originalName) {
  const timestamp = Date.now();
  const random = crypto.randomBytes(8).toString('hex');
  const ext = path.extname(originalName);
  return `${timestamp}-${random}${ext}`;
}

// 确保上传目录存在
export function ensureUploadDir(uploadDir) {
  if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
  }
}

// 验证文件类型
export function validateFileType(file, allowedTypes) {
  const ext = path.extname(file.originalFilename).toLowerCase();
  return allowedTypes.includes(ext);
}

// 验证文件大小（单位：bytes）
export function validateFileSize(file, maxSize) {
  return file.size <= maxSize;
}

// 保存上传文件
export async function saveUploadedFile(file, uploadDir) {
  const fileName = generateUniqueFileName(file.originalFilename);
  const filePath = path.join(uploadDir, fileName);
  
  // 读取临时文件
  const reader = fs.createReadStream(file.filepath);
  // 创建写入流
  const writer = fs.createWriteStream(filePath);
  
  // 写入文件
  await new Promise((resolve, reject) => {
    reader.pipe(writer);
    writer.on('finish', resolve);
    writer.on('error', reject);
  });

  return {
    fileName,
    filePath,
    url: `/uploads/${fileName}` // 返回相对路径
  };
}
